<script lang="ts" setup>
import FormatFormVue from "@/Components/FormatForm.vue";
import PaginationVue from "@/Components/Pagination.vue";
import UpdatePayInfoVue from "./Components/UpdatePayInfo.vue";
import PayInfoExportVue from "./Components/PayInfoExport.vue";

import { ref, reactive, onBeforeMount, watch } from "vue";
import { ElTable, ElMessageBox, Action } from "element-plus";
import { filterExpenses, filterPayStatus } from "@/utils/filters";
import { PayInfoApi, MerchantApi } from "@/Api";

const form = reactive<PayInfo.Search>({
   name: "",
   level: "",
   school: "",
   category: "",
   major: "",
   status: "",
   created_by: "",
   deadline: undefined,
   created_time: undefined,
   prepay_create_time: undefined
});
const formOptions = reactive<FormOptions<PayInfo.Search>>({
   name: {
      type: "text",
      value: "",
      placeholder: "手机号/昵称查询"
   },
   status: {
      type: "select",
      value: "",
      placeholder: "支付状态",
      options: [
         { label: "全部状态", value: "" },
         { label: "已支付", value: "PAID" },
         { label: "开启未创建", value: "OPEN" },
         { label: "创建未支付", value: "NOT_PAID" },
         { label: "取消支付", value: "CANCEL" },
         { label: "关闭", value: "CLOSE" }
      ]
   },
   level: {
      type: "text",
      value: "",
      placeholder: "层次"
   },
   school: {
      type: "text",
      value: "",
      placeholder: "学校"
   },
   category: {
      type: "text",
      value: "",
      placeholder: "报考类别"
   },
   major: {
      type: "text",
      value: "",
      placeholder: "专业"
   },
   created_by: {
      type: "text",
      value: "",
      placeholder: "创建人"
   },
   created_time: {
      type: "datetime",
      value: "",
      placeholders: ["创建时段-开始", "创建时段-结束"]
   },
   deadline: {
      type: "datetime",
      placeholders: ["截至时段-开始", "截至时段-结束"]
   },
   prepay_create_time: {
      type: "datetime",
      placeholders: ["预支付创建时段-开始", "预支付创建时段-结束"]
   }
});
const laypage = reactive<Laypage>({
   pageNum: 1,
   pageSize: 20,
   total: 10
});
const tableData = ref<PayInfo.Table[]>();
const actionInfo = ref<PayInfo.Table>();
const loadingTable = ref(false);
const showUpdatePayInfo = ref(false);
const showPayInfoExport = ref(false);
const merchantList = ref<Merchant.SearchResult[]>();

async function submit() {
   loadingTable.value = true;

   try {
      const params: PaginationSearch<PayInfo.Search> = {
         form,
         laypage
      };

      const res = await PayInfoApi.Search(params);
      if (res.code === 200) {
         const { data } = res;
         tableData.value = data.list;
         laypage.total = data.total;
         laypage.pageNum = data.pageNum;
         laypage.pageSize = data.pageSize;
      }
   } catch (error) {
      console.log("error", error);
   }

   loadingTable.value = false;
}

function sizeChange(num: number) {
   laypage.pageSize = num;
   submit();
}
function currentChange(num: number) {
   laypage.pageNum = num;
   submit();
}

/** 修改缴费信息 */
function handlerUpdate(info: PayInfo.Table) {
   if (!info) return;
   actionInfo.value = info;
   showUpdatePayInfo.value = true;
}

/** 取消缴费信息 */
function handlerClose(info: PayInfo.Table) {
   try {
      ElMessageBox.confirm("取消当前缴费信息?", "警告", {
         confirmButtonText: "确定",
         cancelButtonText: "关闭",
         type: "warning",
         callback: async (action: Action) => {
            if (action === "confirm") {
               const { code } = await PayInfoApi.Delete({ pay_id: info.pay_id });
               if (code === 200) {
                  ElMessage.success("删除成功");
                  await submit();
               }
            }
         }
      });
   } catch (error) {
      console.log("error", error);
   }
}

/** 获取商户列表 */
async function getMerchant() {
   try {
      const { code, data } = await MerchantApi.Search({ status: "OPEN" });
      if (code === 200) merchantList.value = data;
   } catch (error) {
      console.log("error", error);
   }
}

/** 复制文本至剪切板 */
function handlerCopy(text: string) {
   navigator.clipboard
      .writeText(text)
      .then(() => {
         ElMessage.success("复制成功");
      })
      .catch(() => {
         ElMessage.error("复制失败");
      });
}

async function handlerExport() {
   showPayInfoExport.value = true;
}

watch(showUpdatePayInfo, value => {
   if (!value) submit();
});

onBeforeMount(async () => {
   await submit();
   getMerchant();
});
</script>

<template>
   <div class="payInfo">
      <div class="content">
         <FormatFormVue :form="form" :form-options="formOptions" @submit="submit"> </FormatFormVue>
         <div class="tabBox shadowCard">
            <el-table
               v-loading="loadingTable"
               :data="tableData"
               stripe
               border
               highlight-current-row
               empty-text="暂无数据"
               tooltip-effect="dark"
               row-key="id">
               <el-table-column type="selection" width="50" fixed="left" align="center" />
               <el-table-column prop="phone" label="手机号码" width="150" fixed="left">
                  <template #default="{ row }: { row: PayInfo.Table }">
                     <span v-if="!!row.phone" class="phone" @click="handlerCopy(row.phone)">{{ row.phone }}</span>
                  </template>
               </el-table-column>
               <el-table-column prop="name" label="学生姓名" width="85" show-overflow-tooltip />
               <el-table-column prop="fee" label="应缴金额" width="100" align="right" header-align="center">
                  <template #default="{ row }: { row: PayInfo.Table }">
                     {{ filterExpenses(row.fee) }}
                  </template>
               </el-table-column>
               <el-table-column prop="actual_expenses" label="实际支付金额" width="110" align="right" header-align="center">
                  <template #default="{ row }: { row: PayInfo.Table }">
                     {{ filterExpenses(row.actual_expenses) }}
                  </template>
               </el-table-column>
               <el-table-column prop="merchant" label="付款商户" width="100">
                  <template #default="{ row }: { row: PayInfo.InlineTable }">
                     {{ merchantList?.find(item => item.id == row.merchant)?.name || "" }}
                  </template>
               </el-table-column>
               <el-table-column prop="wx_transaction_id" label="微信内部订单号" min-width="150">
                  <template #default="{ row }: { row: PayInfo.Table }">
                     <div class="transaction" v-if="!!row.wx_transaction_id">
                        <el-tooltip effect="dark" :content="'点击复制: ' + row.wx_transaction_id" placement="right">
                           <span @click="handlerCopy(row.wx_transaction_id)">{{ row.wx_transaction_id }}</span>
                        </el-tooltip>
                     </div>
                  </template>
               </el-table-column>
               <el-table-column prop="create_by" label="创建人" width="100" show-overflow-tooltip />
               <el-table-column prop="level" label="层次" show-overflow-tooltip />
               <el-table-column prop="school" label="学校" min-width="150" show-overflow-tooltip />
               <el-table-column prop="category" label="类别" min-width="150" show-overflow-tooltip />
               <el-table-column prop="major" label="专业" min-width="200" show-overflow-tooltip />
               <el-table-column prop="batch" label="批次" />
               <el-table-column prop="school_year" label="学年" />
               <el-table-column prop="description" label="备注" min-width="150" show-overflow-tooltip />
               <el-table-column prop="status" label="支付状态" width="110" align="center">
                  <template #default="{ row }: { row: PayInfo.Table }">
                     {{ filterPayStatus[row.status] }}
                  </template>
               </el-table-column>
               <el-table-column prop="deadline" label="截止时间" width="165" />
               <el-table-column prop="wx_create_time" label="微信创建时间" width="165" />
               <!-- <el-table-column prop="bank_type" label="付款银行" width="100" /> -->
               <el-table-column prop="trade_type" label="交易类型" width="100" />
               <el-table-column prop="success_time" label="支付完成时间" width="165" />
               <el-table-column prop="prepay_create_time" label="预支付创建时间" width="165" />
               <el-table-column prop="created_time" label="创建时间" width="165" />
               <!-- <el-table-column prop="edit_time" label="最后修改时间" width="165" /> -->
               <!-- <el-table-column prop="edit_user" label="最后修改人" width="165" /> -->
               <el-table-column fixed="right" label="操作" width="165" align="center">
                  <template #default="{ row }: { row: PayInfo.Table }">
                     <el-link type="primary" :disabled="row.status !== 'OPEN'" @click="handlerUpdate(row)">
                        <el-icon><Edit /></el-icon> 编辑
                     </el-link>
                     <el-link type="danger" :disabled="row.status !== 'OPEN'" @click="handlerClose(row)">
                        <el-icon><CloseBold /></el-icon> 取消
                     </el-link>
                  </template>
               </el-table-column>
            </el-table>
         </div>
         <PaginationVue :laypage="laypage" @size-change="sizeChange" @current-change="currentChange">
            <!-- <template #left>
               <el-button type="primary" size="small" @click="handlerExport">导出数据</el-button>
            </template> -->
         </PaginationVue>
      </div>

      <UpdatePayInfoVue v-model="showUpdatePayInfo" :pay-info="actionInfo" :merchant-list="merchantList"> </UpdatePayInfoVue>
      <PayInfoExportVue v-model="showPayInfoExport" :search="{ form, laypage }" />
   </div>
</template>

<style lang="scss" scoped>
.payInfo {
   width: 100%;
   height: 100%;
}
.content {
   width: 100%;
   height: 100%;
   display: flex;
   flex-direction: column;
}
.tabBox {
   flex: 1;
   width: 100%;
   position: relative;
   box-sizing: border-box;
   padding: 15px;
   .el-table {
      position: absolute;
      width: calc(100% - 30px);
      height: calc(100% - 30px);

      .el-icon {
         margin-right: 5px;
      }

      .transaction {
         width: 100%;
         height: 100%;
         display: flex;
         align-items: center;
         justify-content: space-between;
         > span {
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
            cursor: pointer;
         }
      }
   }

   .phone {
      cursor: pointer;
   }

   .el-link {
      margin-inline: 5px;
   }
}
</style>
